#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>

// 窗口大小变化回调函数
void framebuffer_size_callback(GLFWwindow *window, int width, int height)
{
    glViewport(0, 0, width, height);
}

// 输入处理
void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

// 清理资源函数
void cleanup(unsigned int VAOs[2], unsigned int VBOs[2], unsigned int shaderProgram) {
    glDeleteVertexArrays(2, VAOs);
    glDeleteBuffers(2, VBOs);
    glDeleteProgram(shaderProgram);
    glfwTerminate();
}

int main()
{
    /**
     * 实例化GLFW窗口
     */
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    /**
     * 创建窗口对象
     */
    GLFWwindow *window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr);
    if (window == nullptr)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }

    //设置OpenGL上下文
    glfwMakeContextCurrent(window);

    /**
     * 初始化GLAD
     */
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        glfwTerminate();
        return -1;
    }

    /**
     * 顶点输入
     *
     */
    // set up vertex data (and buffer(s)) and configure vertex attributes
    // ------------------------------------------------------------------
    float firstTriangle[] = {
        -0.9f, -0.5f, 0.0f, // left
        -0.0f, -0.5f, 0.0f, // right
        -0.45f, 0.5f, 0.0f, // top
    };
    float secondTriangle[] = {
        0.0f, -0.5f, 0.0f, // left
        0.9f, -0.5f, 0.0f, // right
        0.45f, 0.5f, 0.0f  // top
    };

    // 创建顶点数组对象
    unsigned int VAOs[2];
    // 创建顶点缓冲对象
    unsigned int VBOs[2];

    glGenVertexArrays(2, VAOs); // 创建顶点数组对象
    glGenBuffers(2, VBOs);

    glBindVertexArray(VAOs[0]);     // 绑定顶点数组对象
    // 绑定顶点缓冲对象
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
    // 把顶点数据复制到缓冲的内存中
    glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), firstTriangle, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0); // 设置顶点属性指针
    glEnableVertexAttribArray(0);

    glBindVertexArray(VAOs[1]); // 绑定顶点数组对象
    // 绑定顶点缓冲对象
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]);
    // 把顶点数据复制到缓冲的内存中
    glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), secondTriangle, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0); // 设置顶点属性指针
    glEnableVertexAttribArray(0);

    const char *vertexShaderSource = "#version 330 core \n"
                                     "layout(location = 0) in vec3 aPos; \n"
                                     "void main() \n"
                                     "{ \n"
                                     "   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); \n"
                                     "} \n";

    unsigned int vertexShader;
    vertexShader = glCreateShader(GL_VERTEX_SHADER); // 创建顶点着色器对象

    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // 绑定着色器源码
    glCompileShader(vertexShader);                              // 编译顶点着色器

    int success;
    char infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); // 检查编译是否成功
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n"
                  << infoLog << std::endl;
        cleanup(VAOs, VBOs, 0);
        return -1;
    }

    const char *fragmentShaderSource = "#version 330 core \n"
                                       "out vec4 FragColor; \n"
                                       "void main() \n"
                                       "{ \n"
                                       "   FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f); \n"
                                       "} \n";

    unsigned int fragmentShader;
    fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);            // 创建片段着色器对象
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); // 绑定着色器源码
    glCompileShader(fragmentShader);                                // 编译片段着色器

    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); // 检查编译是否成功
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n"
                  << infoLog << std::endl;
        cleanup(VAOs, VBOs, 0);
        return -1;
    }

    // 着色器程序
    unsigned int shaderProgram;
    shaderProgram = glCreateProgram();             // 创建着色器程序对象
    glAttachShader(shaderProgram, vertexShader);   // 把顶点着色器附加到着色器程序上
    glAttachShader(shaderProgram, fragmentShader); // 把片段着色器附加到着色器程序上
    glLinkProgram(shaderProgram);                  // 链接着色器程序

    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); // 检查链接是否成功
    if (!success)
    {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n"
                  << infoLog << std::endl;
        cleanup(VAOs, VBOs, shaderProgram);
        return -1;
    }

    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    glUseProgram(shaderProgram); // 激活着色器程序

    // 注册窗口大小变化回调函数
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    /**
     * 渲染循环

     */
    while (!glfwWindowShouldClose(window))
    {
        processInput(window); // 处理输入

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // 设置清除颜色
        glClear(GL_COLOR_BUFFER_BIT);         // 清除颜色缓冲

        glUseProgram(shaderProgram);      // 使用着色器程序

        glBindVertexArray(VAOs[0]);           // 绑定顶点数组对象
        glDrawArrays(GL_TRIANGLES, 0, 3); // 绘制三角形

        glBindVertexArray(VAOs[1]);       // 绑定顶点数组对象
        glDrawArrays(GL_TRIANGLES, 0, 3); // 绘制三角形

        glfwSwapBuffers(window); // 交换缓冲
        glfwPollEvents();        // 轮询事件
    }

    // 删除缓冲对象和顶点数组对象
    glDeleteVertexArrays(2, VAOs);
    glDeleteBuffers(2, VBOs);
    glDeleteProgram(shaderProgram);

    // 释放资源
    glfwTerminate();

    return 0;
}